package com.partterns.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * java通过反射配置信息构建对象
 */
public class ReflectServiceImpl {
    public void sayHello(String name){
        System.err.println("Hello "+name);
    }
    //给类加载器注册了一个类ReflectServiceImpl的全限定名，然后通过getInstance方法初始化了一个类对象
    //这是无参的类的反射构造方法
    public ReflectServiceImpl getInstance() {
        ReflectServiceImpl object=null;
        try {
            object=(ReflectServiceImpl)Class.forName("com.partterns.reflect.ReflectServiceImpl").newInstance();
        } catch (InstantiationException|IllegalAccessException|ClassNotFoundException e) {
            e.printStackTrace();
        }
        return object;
    }
    //获取和反射方法
    public Object reflectMethod(){
        Object returnObject=null;
        ReflectServiceImpl target=new ReflectServiceImpl();
        try {
            Method method=ReflectServiceImpl.class.getMethod("sayHello", String.class);
            returnObject=method.invoke(target,"张三");
        } catch (NoSuchMethodException|SecurityException|IllegalAccessException|IllegalArgumentException|InvocationTargetException e) {
            e.printStackTrace();
        }
        return returnObject;
    }
}
